<template>
	<view class="login">
		<button v-if="register" open-type="getUserInfo" @getuserinfo='getUserInfo'>微信一键注册</button>
		<input type="text" placeholder="推荐人编号" v-if="options.shareTicket">
	</view>
</template>

<script>
	import {
		login,
		testLogin,
		register,
		getShareInfo
	} from '../../api/login/index.js'
	import {
		getPath,
		setToken
	} from '../../storage/index.js'
	import {mapActions,mapState} from 'vuex'
	
	
	
	export default {
		onLoad() {
			if( this.$Route.query.topUserId){
					this.topUserId = this.$Route.query.topUserId;
			}
			console.log('正在登陆')
			// console.log(JSON.stringify(this.options)+"++++++++++++")
			if (process.env.NODE_ENV === 'development') {
				this.testLogin()
			} else {
				this.login()
			}
			// this.login()

		},
		computed:{
				...mapState({
					options:state=>state.wx.options
				})
		},
		methods: {
			getUserInfo(e) {
				//存在推荐人
				if(this.options.shareTicket){
					this.getShareInfo().then(res => {
						console.log("----+++---=>"+res)
						// 注册
						register(this.topUserId, e.detail.userInfo.nickName, e.detail.userInfo.avatarUrl, this.openId, this.unionId).then(res => {
							console.log(res)
						})
					})
				}
				
			},
			getShareInfo(shareTicket){
					return new Promise((reslove)=>{
						wx.getShareInfo({
							shareTicket:this.options.shareTicket,
							success:(res)=>{
								getShareInfo(res.encryptedData,res.iv).then(res => {
									reslove(res)
								})
							}
						})
					})
			},
			testLogin() {
				let userId = 60115
				
				this.$store.dispatch('updateUser',userId)
				uni.setStorage({
					 key: 'userId',
					 data: userId,
					 success() {
					 	console.log("setStorage")
					 }
				})
				// localStorage.userId=userId
				// console.log('888888')
				testLogin(userId).then(res => {
					if (res.data) {
						this.afterLogin(res)
					} else {
						this.notLogin(res)
					}
					// this.updateUser({userId:res.data.userId})
					// this.$store.dispatch({
					// 	type:'updateUser',
					// 	user: userId
					// })
					
				})
			},
			login() {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						login(loginRes.code).then(res => {
							if (res.data) { // 登录成功
								this.afterLogin(res)
							} else {
								this.notLogin(res)
							}
						})
					}
				})
			},
			afterLogin(res) {
				setToken(res.data.token)
				let path = getPath()
				// console.log(path)
				this.$Router.replace(path)
			},
			notLogin(res) {
				this.openId = res.extra.wxUser.openId
				this.unionId = res.extra.wxUser.unionId
				console.log(this.openId)
				console.log(res.extra.wxUser)
				this.register = true
			},
			...mapActions([
				'updateCartCount',
				'setToken',
				'updateUser'
			])
		},
		data() {
			return {
				topUserId: null,
				register: false,
				openId: null,
				unionId: null
			};
		}
	}
</script>

<style lang="stylus">

</style>
